import React, { Component, Suspense } from "react";
import PageHeaderWrapper from "@/components/PageHeaderWrapper";
import { connect } from "dva";
import PageLoading from "@/components/PageLoading";
import { FormattedMessage,formatMessage } from "umi-plugin-react/locale";
import { Row, Col, Card, Button, Input, message, Icon, Form, Select, AutoComplete, Divider } from "antd";
import { routerRedux } from "dva/router";
import styles from "./index.less";

const EditModal = React.lazy(() => import("./editModal"));
const FieldTable = React.lazy(() => import("./fieldTable"));
const { Option } = Select;
const AutoCompleteOption = AutoComplete.Option;
let responseFieldArr = [];
let requestFieldArr = [];

@connect(({ customApi, loading }) => ({
	customApi,
	loading: loading.effects["customApi/fetchApiDetailById"],
}))
class CustomApi extends Component {
	constructor(props) {
		super(props);
		const { id, urlPrefix } = this.props.match.params;
		this.state = {
			requestField: [],
			responseField: [],
			apiId: null,
			isUsed: false,
			fieldObj: null,
			fieldType: null,
			id,
			urlPrefix,
		};
		this.sysRequestFieldColumns = [
			{
				key: "name",
				align: "left",
				title: formatMessage({id: 'app.customApi.field-business-name'}),
				dataIndex: "name",
				width: "30%",
			},
			{
				key: "id",
				align: "left",
				title: formatMessage({id: 'app.customApi.field-name'}),
				dataIndex: "id",
				width: "30%",
			},
			{
				key: "fieldType",
				align: "left",
				title: formatMessage({id: 'app.customApi.field-type'}),
				dataIndex: "fieldType",
				width: "15%",
			},
			{
				key: "value",
				align: "left",
				title: formatMessage({id: 'app.customApi.field-default-value'}),
				dataIndex: "value",
				width: "15%",
			},
		],
			this.requestFieldColumns = [
				{
					key: "name",
					align: "left",
					title: formatMessage({id: 'app.customApi.field-business-name'}),
					dataIndex: "name",
					width: "30%",
				},
				{
					key: "id",
					align: "left",
					title: formatMessage({id: 'app.customApi.field-name'}),
					dataIndex: "id",
					width: "30%",
				},
				{
					key: "fieldType",
					align: "left",
					title: formatMessage({id: 'app.customApi.field-type'}),
					dataIndex: "fieldType",
					width: "15%",
				},
				{
					key: "value",
					align: "left",
					title: formatMessage({id: 'app.customApi.field-default-value'}),
					dataIndex: "value",
					width: "15%",
				},
				{
					title: formatMessage({id: 'app.customApi.operation'}),
					align: "left",
					width: 200,
					render: (text, row, index) => {
						return (
							<div>
								<Button
									htmlType='button'
									size='small'
									type='primary'
									icon='edit'
									className={styles.processBtn}
									onClick={() => this.editFieldById(row, "requestField", index)}
								>
									<FormattedMessage id='app.processTemplate.btn-edit' />
								</Button>
								<Button
									type='danger'
									htmlType='button'
									size='small'
									icon='delete'
									className={styles.processBtn}
									onClick={() => this.delFieldById(row, "requestField")}
								>
									<FormattedMessage id='app.processTemplate.btn-del' />
								</Button>
							</div>
						);
					},
				},
			];
		this.sysResponseFieldColumns = [
			{
				key: "name",
				align: "left",
				title: formatMessage({id: 'app.customApi.field-business-name'}),
				dataIndex: "name",
				width: "30%",
			},
							{
								key: "id",
								align: "left",
								title: formatMessage({id: 'app.customApi.field-name'}),
								dataIndex: "id",
								width: "30%",
							},
			{
				key: "fieldType",
				align: "left",
				title: formatMessage({id: 'app.customApi.field-type'}),
				dataIndex: "fieldType",
				width: "30%",
			},
		],
			this.responseFieldColumns = [
				{
					key: "name",
					align: "left",
					title: formatMessage({id: 'app.customApi.field-business-name'}),
					dataIndex: "name",
					width: "30%",
				},
				{
					key: "id",
					align: "left",
					title: formatMessage({id: 'app.customApi.field-name'}),
					dataIndex: "id",
					width: "30%",
				},
				{
					key: "fieldType",
					align: "left",
					title: formatMessage({id: 'app.customApi.field-type'}),
					dataIndex: "fieldType",
					width: "30%",
				},
				{
					title: formatMessage({id: 'app.customApi.operation'}),
					align: "left",
					width: 200,
					render: (text, row, index) => {
						return (
							<div>
								<Button
									htmlType='button'
									size='small'
									type='primary'
									icon='edit'
									className={styles.processBtn}
									onClick={() => this.editFieldById(row, "responseField", index)}
								>
									<FormattedMessage id='app.processTemplate.btn-edit' />
								</Button>
								<Button
									type='danger'
									htmlType='button'
									size='small'
									icon='delete'
									className={styles.processBtn}
									onClick={() => this.delFieldById(row, "responseField")}
								>
									<FormattedMessage id='app.processTemplate.btn-del' />
								</Button>
							</div>
						);
					},
				},
			];
	}

	componentDidMount() {
		const { id, urlPrefix } = this.state;
		if (id) {
			this.fetchApiDetailById(id);
		}
		requestFieldArr = [];
		responseFieldArr = [];
	}

	/**
	 * 获取api详情
	 */
	fetchApiDetailById(id) {
		const { dispatch } = this.props;
		const { urlPrefix } = this.state;
		this.reqRef = requestAnimationFrame(() => {
			dispatch({
				type: "customApi/fetchApiDetailById",
				payload: { id: id, urlPrefix },
				callback: (res) => {
					let requestFields = res.requestFields ? res.requestFields : [];
					let responseFields = res.responseFields ? res.responseFields : [];
					requestFieldArr = this.reverseFieldsData(requestFields);
					responseFieldArr = this.reverseFieldsData(responseFields);
					console.log(requestFieldArr);
					this.props.form.setFieldsValue({
						name: res.name,
						url: res.url,
						method: res.method,
						errorMessage: res.errorMessage,
					});
					this.setState({
						isUsed: res.isUsed,
						requestField: requestFieldArr,
						responseField: responseFieldArr,
						fieldObj: res,
					});
				},
			});
		});
	}

	/**
	 * 保存字段
	 */
	pushRequestField = (val, type, method, index, fieldId) => {
		console.log(val, type, method, index, fieldId);
		if (type === "requestField") {
			requestFieldArr = this.deepClone(this.state.requestField);
			if (method === "edit") {
				if (index != null || index != undefined) {
					requestFieldArr[index] = val;
					requestFieldArr[index].fieldId = fieldId;
					requestFieldArr[index].children = undefined;
				} else {
					this.dataFix(val);
				}
			} else {
				val.children = undefined;
				requestFieldArr.push(val);
			}
			this.setState({ requestField: requestFieldArr, });
		} else {
			responseFieldArr = this.deepClone(this.state.responseField);
			if (method === "edit") {
				if (index != null || index != undefined) {
					responseFieldArr[index] = val;
					responseFieldArr[index].children = undefined;
				} else {
					this.dataFix(val);
				}
			} else {
				val.children = undefined;
				responseFieldArr.push(val);
			}
			this.setState({ responseField: responseFieldArr, });
		}
	};

	/**
	 * 字段初始化
	 */
	dataFix(row) {
		const that = this;
		let type = row.type;
		let arr = that.state[type];
		arr.splice(arr.findIndex((v) => v.id === row.id), 1);
	}

	/**
	 * 添加字段
	 */
	addField(type) {
		this.setState({ fieldType: type, }, () => {
			this.EditModal.showModal(type);
		});
	}

	/**
	 * 编辑字段
	 */
	editFieldById(row, requestMethod, index) {
		const that = this;
		let type = requestMethod;
		this.setState({ fieldType: type, }, () => {
			this.EditModal.showModal(type, row, "edit", index);
		});
	}

	/**
	 * 删除字段
	 */
	delFieldById(row, requestMethod) {
		const that = this;
		let type = requestMethod;
		let arr = that.state[type];
		arr.splice(arr.findIndex((v) => v.id === row.id), 1);
		that.setState({ [type]: arr, });
	}

	/**
	 * 跳转接口测试
	 */
	testApi(obj) {
		const { dispatch } = this.props;
		if (!obj || JSON.stringify(obj) === "{}") {
			return message.error("请先保存后，再开始测试");
		}
		this.reqRef = requestAnimationFrame(() => {
			console.log(obj);
			dispatch({
				type: "customApi/test",
				payload: { api: JSON.stringify(obj) },
			});
		});
	}

	/**
	 * 返回接口列表
	 */
	backList() {
		const { dispatch } = this.props;
		dispatch(routerRedux.push("/knowledgeDesign/customApi"));
	}

	/**
	 * 请求字段和返回字段的初始化
	 */
	reverseFieldsData = (data) => {
		for (let item of data) {
			if (item.children && item.children.length > 0) {
				item.name = item.nameZh;
				item.children = undefined;
				// this.reverseFieldsData(item.children);
			} else {
				item.name = item.nameZh;
			}
		}
		return data;
	};

	/** 数据拷贝 */
	deepClone = (target) => {
		let result;
		if (typeof target === "object") {
			if (Array.isArray(target)) {
				result = [];
				for (let i in target) {
					result.push(this.deepClone(target[i]));
				}
			} else if (target === null) {
				result = null;
			} else if (target.constructor === RegExp) {
				result = target;
			} else {
				result = {};
				for (let i in target) {
					result[i] = this.deepClone(target[i]);
				}
			}
		} else {
			result = target;
		}
		return result;
	};

	/**
	 * 保存时请求字段和返回字段的设置
	 */
	setFieldsData = (data) => {
		for (let item of data) {
			if (item.children && item.children.length > 0) {
				let fieldName = item.id;
				let fieldNameZh = item.name;
				item.name = fieldName;
				item.nameZh = fieldNameZh;
				item.children = undefined;
				// this.setFieldsData(item.children);
			} else {
				let fieldName = item.id;
				let fieldNameZh = item.name;
				item.name = fieldName;
				item.nameZh = fieldNameZh;
			}
		}
		return data;
	};

	/**
	 * 字段校验
	 */
	validateFields = (rule, value, callback) => {
		const reg = /(http):\/\/([\w.]+\/?)\S*/;
		if (rule.field === "url") {
			if (value) {
				if (!reg.test(value)) {
					callback("请求地址以HTTP开头");
				}
			} else {
				callback("请求地址以HTTP开头");
			}
		}
	};

	/**
	 * 保存
	 */
	saveApi = () => {
		const { dispatch } = this.props;
		this.props.form.validateFields((err, values) => {
			if (!err) {
				let requestFieldData = this.deepClone(this.state.requestField);
				let responseFieldData = this.deepClone(this.state.responseField);
				let requestField = this.setFieldsData(requestFieldData);
				let responseField = this.setFieldsData(responseFieldData);
				let url = "customApi/add";
				let obj = {
					name: values.name,
					url: values.url,
					method: values.method,
					errorMessage: values.errorMessage,
					requestFields: requestField,
					responseFields: responseField,
				};
				if (this.state.id) {
					obj.id = this.state.id;
					url = "customApi/edit";
				}
				dispatch({
					type: url,
					payload: obj,
					callback: (res) => {
						console.log(res);
						if (typeof res.code !== 'undefined' && res.code !== 0) {
							// message["error"](`${res.message}`);
						} else {
							if (res.data) {
								obj["apiId"] = res.data;
								this.setState({ apiId: res.data, });
							}
							message.info(res.message);
							setTimeout(() => {
								this.backList();
							}, 500);
						}
					},
				});
			}
		});
	};

	render() {
		const { getFieldDecorator } = this.props.form;
		const formItemLayout = {
			labelCol: { span: 3 },
			wrapperCol: { span: 14 },
		};
		const formItemLayoutForTable = {
			labelCol: { span: 3 },
			wrapperCol: { span: 14, offset: 3 },
		};
		const { currentUser } = this.props;
		const { urlPrefix } = this.state;
		return (
			<Suspense fallback={<PageLoading />}>
				<PageHeaderWrapper>
					<Card>
						<Row>
							<Col span={18}>
								<div className={styles.title}>
									<FormattedMessage id='app.customApi.title-edit' />
								</div>
							</Col>
							<Col span={6}>
								<div
									style={{
										paddingTop: 16,
										paddingRight: 20,
										color: "rgb(21,144,255)",
										cursor: "pointer",
										textAlign: "right",
									}}
									onClick={() => this.backList()}
								>
									<Icon type='bars' style={{ marginRight: 5 }} />
									<FormattedMessage id='app.customApi.backList' />
								</div>
							</Col>
						</Row>
						<Divider style={{ margin: "12px 0" }} />
						<Row>
							<Col span={24}>
								<Form {...formItemLayout}>
									<Form.Item label={<FormattedMessage id='app.customApi.apiName' />}>
										{getFieldDecorator("name", {
											rules: [
												{
													required: true,
													message: formatMessage({id: 'app.customApi.api-name-required'}),
												},
											],
										})(<Input placeholder={formatMessage({id: 'app.customApi.api-name-placeholder'})} maxLength={200} />)}
									</Form.Item>
									<Form.Item label={<FormattedMessage id='app.customApi.requestMethod' />}>
										{getFieldDecorator("method", {
											rules: [
												{
													required: true,
													message: formatMessage({id: 'app.customApi.request-method-required'}),
												},
											],
										})(
											<Select>
												<Option value='GET'>GET</Option>
												<Option value='POST'>POST</Option>
											</Select>
										)}
									</Form.Item>
									<Form.Item label={<FormattedMessage id='app.customApi.requestAddress' />}>
										{getFieldDecorator("url", {
											rules: [
												{
													required: true,
													message: formatMessage({id: 'app.customApi.request-address-required'}),
													whitespace: true,
												},
												{
													// validator: this.validateFields,
												},
											],
										})(
											<Input
												placeholder={formatMessage({id: 'app.customApi.request-address-placeholder'})}
												maxLength={200}
											/>
										)}
									</Form.Item>
									<Form.Item label={<FormattedMessage id='app.customApi.requestField' />}>
										{
											<Button
												type='dashed'
												htmlType='button'
												disabled={urlPrefix && currentUser.tenantId != 2}
												icon='plus'
												style={{ backgroundColor: "skyblue", color: "#fff" }}
												onClick={() => this.addField("requestField")}
											>
												<FormattedMessage id='app.customApi.add' />
											</Button>
										}
									</Form.Item>
									<Form.Item {...formItemLayoutForTable}>
										<FieldTable
											data={this.state.requestField}
											columns={urlPrefix && currentUser.tenantId != 2 ? this.sysRequestFieldColumns : this.requestFieldColumns}
										/>
									</Form.Item>
									<Form.Item label={<FormattedMessage id='app.customApi.responseField' />}>
										{
											<Button
												type='dashed'
												htmlType='button'
												icon='plus'
												disabled={urlPrefix && currentUser.tenantId != 2}
												style={{
													backgroundColor: "orange",
													color: "#fff",
												}}
												onClick={() => this.addField("responseField")}
											>
												<FormattedMessage id='app.customApi.add' />
											</Button>
										}
									</Form.Item>
									<Form.Item {...formItemLayoutForTable}>
										<FieldTable
											data={this.state.responseField}
											columns={urlPrefix && currentUser.tenantId != 2 ? this.sysResponseFieldColumns : this.responseFieldColumns}
										/>
									</Form.Item>
									<Form.Item label={<FormattedMessage id='app.customApi.Call-Failed-the-art-of-speaking' />}>
										{getFieldDecorator("errorMessage", {
											rules: [
												{
													required: true,
													message: formatMessage({id: 'app.customApi.error-message-required'}),
												},
											],
										})(
											<Input placeholder={formatMessage({id: 'app.customApi.error-message-placeholder'})} maxLength={200} />
										)}
									</Form.Item>
									<Form.Item {...formItemLayoutForTable}>
										<Button
											htmlType='button'
											onClick={() => {
												this.testApi(this.state.fieldObj);
											}}
										>
											<FormattedMessage id='app.customApi.apiTest' />
										</Button>
										<Button
											type='primary'
											style={{ marginLeft: 10 }}
											disabled={urlPrefix && currentUser.tenantId != 2}
											onClick={this.saveApi}
										>
											<FormattedMessage id='app.customApi.apiSave' />
										</Button>
									</Form.Item>
								</Form>
							</Col>
						</Row>
						<EditModal
							wrappedComponentRef={(e) => (this.EditModal = e)}
							addRequestFieldFun={this.pushRequestField}
						/>
					</Card>
				</PageHeaderWrapper>
			</Suspense>
		);
	}
}

export default connect(({ user }) => ({
	currentUser: user.currentUser,
}))(Form.create()(CustomApi));